package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.*;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrdersettinglistService.class)
@Transactional
public class OrdersettinglistServiceImpl implements OrdersettinglistService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private OrderSettingListDao orderSettingListDao;

    //orderDate: "2019-11-13T16:00:00.000Z"
//orderStatus: "未到诊"
//orderType: "微信预约"
//setmeal: "堕胎"
//telephone: "18792084140"
//username: "啊"
    //新增预约
    public Result add(Map<String, Object> map) throws Exception {
        String username = (String) map.get("username");
        String telephone = (String) map.get("telephone");
        String orderType = (String) map.get("orderType");
        String orderStatus = (String) map.get("orderStatus");
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        String setmeal = (String) map.get("setmeal");
        String idCard = (String) map.get("idCard");
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行
          //检查所选日期是否失效
        long time = new Date().getTime();
        long time1 = date.getTime();
        if(time>time1){
            return new Result(false,"所选日期已失效");
        }
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null) {//没有设置
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //已设置
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约

        int number = orderSetting.getNumber();//可预约
        int reservations = orderSetting.getReservations();//已预约
        if (number <= reservations) {//约满
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //可预约
        //防止重复预约
        //从会员表中根据手机号码查询查询

        Member m = memberDao.findByTelephone(telephone);

        if (m == null) {//该用户不是会员
//           收集信息,为其注册(添加)
            m = new Member();
            m.setIdCard(idCard);
            m.setRegTime(new Date());
            m.setPhoneNumber(telephone);
            m.setName(username);
            memberDao.add(m);
        }
        //用户是会员
        Integer mid = m.getId();
        //通过套餐名查询对应id
        Setmeal setmeal1 = setmealDao.findSetmealByname(setmeal);
        Integer sid = setmeal1.getId();
        //封装到order中,查询
        Order order = new Order(mid, date, sid);
        List<Order> orderList = orderDao.findByCondition(order);
        if (orderList != null && orderList.size() > 0) {
            //已经预约
            return new Result(false, MessageConstant.HAS_ORDERED);//不能重复预约(相同手机相同套餐同一天预约)
        }

        //可以预约,设置ordersetting加1
        orderSetting.setReservations(reservations + 1);
        //数据库修改
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        //保存到order
        Order orders = new Order(mid, date, orderType, orderStatus, sid);
        orderDao.add(orders);
        return new Result(true, MessageConstant.ORDER_SUCCESS);//预约成功

    }

    //分页查询
    public PageResult pageQuery(Map map) throws Exception {
/*currentPage: 1
name: ""
orderDate: ["2019-11-05", "2019-12-11"]
orderStatus: ""
orderType: ""
pageSize: 10
phoneNumber: ""
username: ""
* */
        //获取分页条件
        Integer currentPage = (Integer) map.get("currentPage");
        Integer pageSize = (Integer) map.get("pageSize");
        PageHelper.startPage(currentPage, pageSize);
        //对日期范围处理
        List<String> list = null;
        try {
            list = (List<String>) map.get("orderDate");
        } catch (Exception e) {
            /*e.printStackTrace();*/
            list = null;
            map.put("orderDate",list);
        }
        if (list != null && list.size() > 0) {
            Date begin = DateUtils.parseString2Date(list.get(0));
            Date end = DateUtils.parseString2Date(list.get(1));

            //将数据封装到集合
            map.put("begin", begin);
            map.put("end", end);
        }


        Page<Map> page = orderDao.findByConditions(map);

        return new PageResult(page.getTotal(), page.getResult());

    }

    //通过订单id查询多表
    public Orderlist findById(Integer id) {
        //通过id查询订单
        Order order = orderDao.findById(id);
        //通过order的member_id查询用户和号码
        Member member = memberDao.findById(order.getMemberId());
        //通过order的setmeal_id查询套餐
        Setmeal setmeal = setmealDao.findById(order.getSetmealId());
        Orderlist orderlist = new Orderlist(order.getId(), member.getName(),
                setmeal.getName(), member.getPhoneNumber(),
                order.getOrderDate(), order.getOrderType(),
                order.getOrderStatus(), member.getIdCard());
        return orderlist;
    }

    //编辑
    public Result edit(Orderlist orderlist) {

        Date date = orderlist.getOrderDate();
        String phoneNumber = orderlist.getPhoneNumber();
        String username = orderlist.getUsername();
        Integer id = orderlist.getId();
        String idCard = orderlist.getIdCard();
        String name = orderlist.getName();
        String orderStatus = orderlist.getOrderStatus();
        String orderType = orderlist.getOrderType();
        long time = new Date().getTime();
        long time1 = date.getTime();
        if(time>time1){
            return new Result(false,"所选日期已失效");
        }
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null) {//没有设置
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //已设置
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约
        int reservations = orderSetting.getReservations();//已预约
        if (number <= reservations) {//约满
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //防止重复预约

        //从会员表中根据手机号码查询查询
        Member m = memberDao.findByTelephone(phoneNumber);

        if (m == null) {//该用户不是会员
//           收集信息,为其注册(添加)
            m = new Member();
            m.setIdCard(idCard);
            m.setRegTime(new Date());
            m.setPhoneNumber(phoneNumber);
            m.setName(username);
            memberDao.add(m);
        }
        //用户是会员
        Integer memberId = m.getId();
        //通过套餐名查询对应id
        Setmeal setmeal = setmealDao.findSetmealByname(name);
        Integer setmealId = setmeal.getId();
        Order order = new Order(memberId, date, null, null, setmealId);
        List<Order> list = orderDao.findByCondition(order);
        if (list != null && list.size() > 0) {
            //已经完成了预约，不能重复预约
            return new Result(false, MessageConstant.HAS_ORDERED);
        }

        //3可以修改

//         3.1 修改member(name,phone,idCard)
        //通过号码查询member得到其id
        Member m1 = new Member(memberId, username, idCard, phoneNumber);
        memberDao.edit(m1);
        //修改order
        Order o = new Order(id, memberId, date, orderType, orderStatus, setmealId);
        orderDao.edit(o);
        return new Result(true, "编辑成功");
    }

    //删除
    public void delete(Integer id) {
        //检查address表与order表关系,通过订单id查询中间表有无数据
        Integer count = orderDao.findCountByOrderId(id);
        if (count > 0) {//被引用,删除与地址关联
            orderDao.deleteAssociation(id);
        }
        orderDao.delete(id);
    }


    //修改状态
    public void editstatus(Orderlist orderlist) {

        Order order = new Order();
        order.setId(orderlist.getId());
        order.setOrderStatus(orderlist.getOrderStatus());
        orderDao.editstatus(order);
    }
}
